﻿@{
    ViewBag.Title = "微信菜单管理";
}

@section css
{
    <style>
        .treeviewPanel {
            margin-right: 10px;
        }

            .treeviewPanel .treeview {
                width: 240px;
            }

        .treeview .list-group-item {
            cursor: pointer;
            position: relative;
            display: block;
            padding: 10px 15px;
            margin-bottom: -1px;
            background-color: #fff;
            border: 1px solid #ddd;
        }

            .treeview .list-group-item:first-child {
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
            }

        .treeview span.indent {
            margin-left: 20px;
            margin-right: 10px;
        }

        .treeview span.icon {
            width: 12px;
            margin-right: 5px;
        }

        .treeview .node-disabled {
            color: silver;
            cursor: not-allowed;
        }

        .node-treeview {
            color: #428bca;
        }

            .node-treeview:not(.node-disabled):hover {
                background-color: #F5F5F5;
            }

        .treeview .node-selected {
            color: #FFFFFF;
            background-color: #428bca;
        }
    </style>
}

<div style="float:right">
    <a class="layui-btn layui-btn-small layui-btn-normal"  onclick="memuSyn()">
        <i class="layui-icon">&#x1002;</i>同步到公众号
    </a>
    <a class="layui-btn layui-btn-small layui-btn-normal" onclick="memuAdd()">
        <i class="layui-icon">&#xe608;</i>添加菜单
    </a>
    <a class="layui-btn layui-btn-small layui-btn-warm" onclick="memuUpdate()">
        <i class="layui-icon">&#xe642;</i>编辑菜单
    </a>
    <a class="layui-btn layui-btn-small layui-btn-danger" onclick="memuDelete()">
        <i class="layui-icon">&#xe640;</i>删除菜单
    </a>
</div>

<div class="treeviewPanel">
    <div class="treeview">

    </div>
</div>

@section htmls
{
    <div id="wechatLayer" style="display:none;padding:15px">
        <div class="layui-form">
            <input type="hidden" name="WechatId" class="layui-input">
            <div class="layui-form-item">
                <label class="layui-form-label">栏目名称</label>
                <div class="layui-input-block">
                    <input type="text" name="WechatName" lay-verify="wechatname" autocomplete="true" placeholder="请输入栏目名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">所属栏目</label>
                <div class="layui-input-block">
                    <select name="WechatParentId" lay-verify="wechatparentid" lay-search="true">
                        <option value="0">请选择</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">排序</label>
                    <div class="layui-input-inline">
                        <input type="tel" name="WechatSort" lay-verify="wechatsort" autocomplete="true" class="layui-input">
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">栏目类型</label>
                    <div class="layui-input-block">
                        <input type="radio" name="WechatType" value="click" checked="checked" title="消息回复">
                        <input type="radio" name="WechatType" value="view" title="跳转">
                        <input type="radio" name="WechatType" value="scancode_waitmsg" title="扫码带提示">
                        <input type="radio" name="WechatType" value="scancode_push" title="扫码推事件">
                        <input type="radio" name="WechatType" value="pic_sysphoto" title="系统拍照发图">
                        <input type="radio" name="WechatType" value="pic_photo_or_album" title="拍照或者相册发图">
                        <input type="radio" name="WechatType" value="pic_weixin" title="微信相册发图">
                        <input type="radio" name="WechatType" value="location_select" title="发送位置">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="wechatLayer">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </div>
    </div>
}

@section scripts
{
    <script>
        var form = null;
        var layer = null;
        var memuManager = null;
        layui.use('layer', function () {
            layer = layui.layer;
        });

        layui.use('form', function () {
            form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
            form.verify({
                wechatname: [
                    /[\u4e00-\u9fa5]{2,6}/
                    , '栏目长度必须在2-6位'
                ],
                wechatsort: [
                    /[0-9]\d*/
                    , '排序只能输入正整数'
                ]
            })
            //……
            form.on('submit(wechatLayer)', function (dom) {

                //被执行事件的元素DOM对象，一般为button对象
                console.log(dom.form) //被执行提交的form对象，一般在存在form标签时才会返回

                var url = "/wechat/WechatMemuAjax"
                var parms = dom.field;
                parms.sub = "insertOrUpdateMemu"
                $(dom.elem).html('正在提交中...')
                    .attr('disabled', 'disabled')
                $.post(url, parms, function (datas) {
                    $(dom.elem).html('立即提交')
                        .removeAttr('disabled')
                    var data = JSON.parse(datas)
                    layer.msg(data.message)
                    if (data.status) {
                        layer.closeAll('page')
                        loadMenu();
                    }
                }).error(function (datas) {
                    $(dom.elem).html('立即提交')
                        .removeAttr('disabled')
                })
                return false;
            });
            //但是，如果你的HTML是动态生成的，自动渲染就会失效
            //因此你需要在相应的地方，执行下述方法来手动渲染，跟这类似的还有 element.init();
            form.render();
        });

        function memuAdd() {
            memuManager.MemuUpdate = false;
            memuManager.WechatLayerLoad();
        }

        function memuUpdate() {
            memuManager.MemuUpdate = true;
            if (treeManager.SelectedNode == null) {
                layer.msg('请选择要修改的微信菜单')
                return;
            }
            memuManager.WechatLayerLoad();
        }

        function memuSyn() {
            layer.confirm('确认同步微信菜单？',
                {
                    icon: 3,
                    title: "同步微信菜单",
                    btn: ['确认', '取消']
                }, function () {
                    var url = "/Wechat/WechatMemuAjax?sub=synchronizeMemu"
                    $.post(url,
                        function (datas) {
                            var data = JSON.parse(datas);
                            layer.msg(data.message)
                            if (data.status)
                                loadMenu();
                        })
                }
            )
        }

        function memuDelete() {
            if (treeManager.SelectedNode == null) {
                layer.msg('请选择要修改的微信菜单')
                return;
            }
            layer.confirm('如果含有子菜单将一并删除',
                {
                    icon: 3,
                    title: '确认删除吗？',
                    btn: ['确认', '取消'] //按钮
                }, function () {
                    var url = "/Wechat/WechatMemuAjax"
                    $.post(url,
                        {
                            sub: "deleteMemu",
                            WechatId: treeManager.SelectedNode.id
                        }, function (datas) {
                            var data = JSON.parse(datas);
                            layer.msg(data.message)
                            if (data.status)
                                loadMenu();
                        })
                })
        };

        MemuManager.prototype.WechatLayerLoad = function () {
            var that = this;
            var parentId = 0;

            if (treeManager.SelectedNode != null)
                parentId = treeManager.SelectedNode.id;
            if (that.MemuUpdate) {

                that.$memu.val(treeManager.SelectedNode.parentId);
                that.$name.val(treeManager.SelectedNode.name);
                that.$id.val(treeManager.SelectedNode.id);
                that.$sort.val(treeManager.SelectedNode.sort);
                that.$type.val(treeManager.SelectedNode.type);
                $("input[type='radio'][value='" + treeManager.SelectedNode.type + "']")[0].checked = true;
            } else {
                if (treeManager.SelectedNode != null) {
                    if (treeManager.SelectedNode.parentId != 0) {
                        //layer.msg('微信公众号最多支持两级')
                        that.$memu.val(0);
                    } else {
                        that.$memu.val(treeManager.SelectedNode.id);
                    }
                } else {
                    that.$memu.val(0);
                }

                that.$name.val('');
                that.$id.val('0');
                that.$sort.val('');
                $("input[type='radio']")[0].checked = true;
            }
            form.render();
            layer.open({
                type: 1,
                shade: 0.1,
                title: '添加微信菜单',
                area: ['500px', '450px'],
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                content: $("#wechatLayer"),
            });
        }

        function TreeManager() {
            this.Nodes = [];
            this.SelectNode = null;
        }

        function MemuManager() {
            this.MemuNodes = [];
            this.MemuId = 0;
            this.$memu = null;
            this.$name = null;
            this.$id = null;
            this.$sort = null;
            this.$type = null;
            this.MemuUpdate = false;
        }

        TreeManager.prototype.DrawTree = function () {
            var that = this;
            $(".treeview").html("");
            if (that.Nodes.length > 0) {
                $ul = $("<ul>")
                for (var i = 0; i < that.Nodes.length; i++) {
                    that.DrawNode(0, $ul, that.Nodes[i]);
                }
                $(".treeview").append($ul);

                $(".treeview li").bind('click', function () {
                    that.NodeClick(that, this);
                })

                $(".treeview li i.expand-icon").bind("click", function () {
                    var e = window.event || event;
                    if (e && e.stopPropagation) {
                        e.stopPropagation();
                    } else {
                        window.event.cancelBubble = true;
                    }
                    that.ExpandNode(that, this);
                });
            }
        }

        TreeManager.prototype.DrawNode = function (level, $parentHtml, node) {
            var that = this;
            $li = $("<li>");
            $li.addClass("list-group-item");
            $li.attr("data-nodeid", node.id);
            if (that.SelectedNode != null && that.SelectedNode.Id == node.id) {
                $li.addClass("node-selected");
            }
            if (level > 0) {
                for (var i = 0; i < level; i++) {
                    $li.append("<span class='indent'></span>");
                }
            }
            var $icon = $('<i class="layui-icon"></i>');

            if (node.nodes.length > 0) {
                $icon.addClass("expand-icon");
                if (node.isExpand == 1) {
                    $icon.html("&#xe61a;");
                }
                else {
                    $icon.html("&#xe619;");
                }
            }
            $li.append($icon);
            $li.append("<span class='icon node-icon'></span>");
            $li.append(node.name);
            $parentHtml.append($li);
            for (var i = 0; node.isExpand == 1 && i < node.nodes.length; i++) {
                that.DrawNode(level + 1, $parentHtml, node.nodes[i]);
            }

        }

        TreeManager.prototype.ExpandNode = function (that, span) {
            var $li = $(span).parents("li");
            var node = that.GetNodeById(that.Nodes, $li.attr("data-nodeid"));
            node.isExpand = (node.isExpand + 1) % 2;
            that.DrawTree();
        }

        TreeManager.prototype.NodeClick = function (that, li) {
            var $li = $(li);
            var nodeId = $li.attr('data-nodeid');
            if (that.SelectedNode == null || that.SelectedNode.nodeId != nodeId) {
                $("li.node-selected").removeClass('node-selected')
                $li.addClass('node-selected');
                that.SelectedNode = that.GetNodeById(that.Nodes, nodeId);
            } else if (that.SelectedNode.nodeId == nodeId) {
                $li.removeClass('node-selected');
                that.SelectedNode = null;
            }
        }

        TreeManager.prototype.GetNodeById = function (nodes, nodeId) {
            var that = this;
            if (nodes.length > 0) {
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].id == nodeId) {
                        return nodes[i];
                    }
                    else {
                        if (nodes[i].nodes.length > 0) {
                            var node = that.GetNodeById(nodes[i].nodes, nodeId);
                            if (node != null) {
                                return node;
                            }
                        }
                    }
                }
            }
            return null;
        }

        var treeManager = null;

        $(document).ready(function () {
            treeManager = new TreeManager();
            memuManager = new MemuManager();
            loadMenu();
        })

        function loadMenu() {
            var url = "/Wechat/WechatMemuAjax";
            $.post(url, { sub: "getMemu" }, function (datas) {
                var data = JSON.parse(datas);
                if (data.status) {
                    treeManager.Nodes = data.data;
                    treeManager.SelectNode = null;
                    treeManager.DrawTree();
                    memuManager.MemuNodes = data.data;
                    memuManager.DrawOption();
                } else {
                    $(".treeview").html("目前还没有微信菜单")
                }
            }, "json")
        }

        MemuManager.prototype.DrawOption = function () {
            var that = this;
            if (this.$memu == null) {
                that.$memu = $("[name=WechatParentId]");
                that.$name = $("[name=WechatName]");
                that.$id = $("[name=WechatId]");
                that.$sort = $("[name=WechatSort]");
                that.$type = $("[name=WechatType]");
            }

            that.$memu.html('')
            var $option = $("<option ></option>")
            $option.attr('value', '0');
            $option.html('请选择');
            that.$memu.append($option);
            for (var i = 0; i < that.MemuNodes.length; i++) {
                if (that.MemuNodes[i].parentId == 0) {
                    $option = $("<option ></option>")
                    $option.attr('value', that.MemuNodes[i].id);
                    $option.html(that.MemuNodes[i].name);
                    that.$memu.append($option);
                }
            }
            form.render();
        }

    </script>
}
